package com.lagou.sqlsession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {


    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {

        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Class<?> classType = simpleExecutor.getClassType("com.lagou.config.BoundSql");
        Field declaredField = classType.getDeclaredField("sqlTest");
        declaredField.setAccessible(true);
        BoundSql o = (BoundSql) classType.newInstance();
        declaredField.set(o,"123");
        System.out.println(o.getSqlTest());

    }


    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1.注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        // 2.获取sql
        String sql = mappedStatement.getSql();
        // 定义一个sql方法来解析这个sql
        BoundSql boundSql = getBoundSql(sql);
        // 3.获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());
        // 4.设置参数
        // 获取参数全路径
        String paramterType = mappedStatement.getParamterType();
        // 得到class对象
        Class<?> paramterTypeClass = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i=0;i<parameterMappingList.size();i++){
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        // 6.封装结果集
        while(resultSet.next()){
            Object o = resultTypeClass.newInstance();
            // 获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for(int i=1;i<=metaData.getColumnCount();i++){
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的value，要保证数据库和实体类属性一致
                Object value = resultSet.getObject(columnName);
                // 使用反射或自省完成数据库和实体类的封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);
        }


        return (List<E>) objects;
    }

    @Override
    public int insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 注册驱动
        Connection connection = configuration.getDataSource().getConnection();
        // 获取sql
        String sql = mappedStatement.getSql();
        // 定义一个sql方法来解析这个sql
        BoundSql boundSql = getBoundSql(sql);
        // 获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());
        // 设置参数
        // 获取参数全路径
        String paramterType = mappedStatement.getParamterType();
        // 得到class对象
        Class<?> paramterTypeClass = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i=0;i<parameterMappingList.size();i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int i = preparedStatement.executeUpdate();
        return i;

    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        // 获取驱动
        Connection connection = configuration.getDataSource().getConnection();
        // 获取sql
        String sql = mappedStatement.getSql();
        // 把sql进行解析放入预编译语句中
        BoundSql boundSql = getBoundSql(sql);
        // 获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());
        // 通过反射拿到对象
        Class<?> paramterTypeClass = getClassType(mappedStatement.getParamterType());

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i=0;i<parameterMappingList.size();i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        int i = preparedStatement.executeUpdate();
        return i;



    }

    @Override
    public int deleteUser(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception{
        // 获取驱动
        Connection connection = configuration.getDataSource().getConnection();
        // 获取sql
        String sql = mappedStatement.getSql();
        // 把sql进行解析放入预编译语句中
        BoundSql boundSql = getBoundSql(sql);
        // 获取预编译对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());
        // 通过反射拿到对象
        Class<?> paramterTypeClass = getClassType(mappedStatement.getParamterType());
        if(null == paramterTypeClass){
            throw new RuntimeException("没有获取到对应的paramterType");
        }

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i=0;i<parameterMappingList.size();i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射
            if(paramterTypeClass.getName().equals("java.lang.Integer")){
                preparedStatement.setObject(i+1,params[0]);
            }else{


            Field declaredField = paramterTypeClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
            }
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }

    private Class<?> getClassType(String param) throws ClassNotFoundException {
        if(param!=null){
            Class<?> aClass = Class.forName(param);
            return aClass;
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作  1.将里边的#{}换成？  2.将#{}里边的值提取出来封装到一个对象里边
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类：配置标志解析器完成对占位符的解析处理工作
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{","}",handler);
        // 返回解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        // 拿到sql里边的属性
        List<ParameterMapping> parameterMappings = handler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;






    }
}
